package com.example.controller;

import com.example.entity.FoodsCategory;
import com.example.service.FoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/foodscategory")
public class FoodsCategoryController {

    @Autowired
    private FoodsCategoryService foodsCategoryService;

    // 显示所有分类列表
    @GetMapping("/list")
    public String list(Model model) {
        List<FoodsCategory> categories = foodsCategoryService.getAllFoodsCategories();
        model.addAttribute("categories", categories);  // 确保属性名与JSP中的一致
        return "foodscategory/list";  // 对应/WEB-INF/views/foodscategory/list.jsp
    }
    // 显示添加分类表单
    @GetMapping("/add")
    public String toAddPage() {
        return "foodscategory/add";
    }

    // 处理添加分类请求
    @PostMapping("/add")
    public String add(FoodsCategory category, RedirectAttributes redirectAttributes) {
        int result = foodsCategoryService.addFoodsCategory(category);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "分类添加成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "分类添加失败");
        }
        return "redirect:/foodscategory/list";
    }

    // 显示编辑分类表单
    @GetMapping("/edit/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        FoodsCategory category = foodsCategoryService.getFoodsCategoryById(id);
        model.addAttribute("category", category);
        return "foodscategory/edit";
    }

    // 处理编辑分类请求
    @PostMapping("/edit")
    public String edit(FoodsCategory category, RedirectAttributes redirectAttributes) {
        int result = foodsCategoryService.updateFoodsCategory(category);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "分类更新成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "分类更新失败");
        }
        return "redirect:/foodscategory/list";
    }

    // 处理删除分类请求
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, RedirectAttributes redirectAttributes) {
        int result = foodsCategoryService.deleteFoodsCategory(id);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "分类删除成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "分类删除失败");
        }
        return "redirect:/foodscategory/list";
    }
}